#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, time, traceback, Queue, Ice
Ice.loadSlice('MotorGrid.ice', ['-I' '/usr/share/slice'])
import Demo

class Trabajo (object):
    def __init__ (self, cb, grid, factor):
        self._cb = cb
        self._grid = grid
        self._factor = factor
        self.ejecutar()

    def ejecutar (self):
        if not self.interpolarGrid():
            self._cb.ice_exception(Demo.ErrorDeRango())
            return
        self._cb.ice_response(self._grid)

    def interpolarGrid (self):
        if len(self._grid) > 1:
            for i in range (0, len(self._grid)):
                for j in range (0, len(self._grid[i])):
                    self._grid[i][j] *= self._factor
            return True
        else:
            return False

class ModelI (Demo.Model):
    def __init__ (self):
        self._trabajos = Queue.Queue()

    def interpolar_async (self, cb, datos, factor, current = None):
        self._trabajos.put(Trabajo(cb, datos, factor))

class Server (Ice.Application):
    def run (self, argv):
        self.shutdownOnInterrupt()
        adapter = self.communicator().createObjectAdapterWithEndpoints(
            'MotorGridAdapter', 'default -p 10000')
        adapter.add(ModelI(), Ice.stringToIdentity('MotorGrid'))
        adapter.activate()
        self.communicator().waitForShutdown()
        return 0

Server().main(sys.argv)
